package com.myself.cloud.service.exception;

import com.myself.cloud.entity.ErrorCodeEnum;
import com.myself.cloud.service.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * 异常错误类
 */
@Component
public class BusinessException extends RuntimeException {
    private ErrorCodeEnum exceptionEnum;
    private String code;
    private String errorMsg;

    public BusinessException() {
        super();
    }

    public BusinessException(ErrorCodeEnum exceptionEnum) {
        super("{code:" + exceptionEnum.getCode() + ",errorMsg:" + exceptionEnum.getMsg() + "}");
        this.exceptionEnum = exceptionEnum;
        this.code = exceptionEnum.getCode();
        this.errorMsg = exceptionEnum.getMsg();
    }

    public BusinessException(String code, String errorMsg) {
        super("{code:" + code + ",errorMsg:" + errorMsg + "}");
        if (StringUtils.isEmpty(code)) {
            this.code = ErrorCodeEnum.UNKNOWN.getCode();
            this.errorMsg = errorMsg;
        } else {
            this.code = code;
            this.errorMsg = StringUtils.isEmpty(errorMsg) ? RedisUtil.getErrorMsg(code) : errorMsg;
        }
    }

    public BusinessException(String code) {
        super("{code:" + code);
        if (StringUtils.isEmpty(code)) {
            this.code = ErrorCodeEnum.UNKNOWN.getCode();
            this.errorMsg = "";
        } else {
            this.code = code;
            this.errorMsg = RedisUtil.getErrorMsg(code);
        }
    }

    public BusinessException(String code, String errorMsg, Object... args) {
        super("{code:" + code + ",errorMsg:" + String.format(errorMsg, args) + "}");
        this.code = code;
        this.errorMsg = String.format(errorMsg, args);
    }

    public ErrorCodeEnum getExceptionEnum() {
        return exceptionEnum;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}
